import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class ApiInterceptors {
  // 单例模式确保整个应用只有一个Dio实例
  static final Dio _dio = Dio(BaseOptions(
    baseUrl: 'http://192.168.3.61:5000', // 设置基础URL
    connectTimeout: const Duration(seconds: 5), // 设置连接超时时间（毫秒）
    receiveTimeout: const Duration(seconds: 5), // 设置响应接收超时时间（毫秒）
  ));

  // 返回Dio实例，便于在其他地方添加额外的配置（如拦截器）
  static Dio get dio => _dio;

  ApiInterceptors() {
    // 添加拦截器示例，可在此处添加全局请求/响应拦截逻辑
    addInterceptors();
  }

  // 拦截器示例，可在此处添加全局请求/响应拦截逻辑
  static void addInterceptors() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          debugPrint('onRequest baseUrl: ${options.baseUrl}');
          debugPrint('onRequest path: ${options.path}');
          return handler.next(options);
        },
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          debugPrint('onResponse response: $response');
          return handler.next(response);
        },
        onError: (DioException error, ErrorInterceptorHandler handler) {
          debugPrint('onError error: $error');
          return handler.next(error);
        },
      ),
    );
  }

  // 默认错误处理方法
  static void handleDioError(DioException error) {
    // 根据错误类型和状态码进行相应处理，如提示用户、重试请求等
    debugPrint('Error: ${error.message}, Status Code: ${error.response?.statusCode}');
  }

  // GET请求方法
  Future<T?> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
    Function(T?)? onSuccess,
    Function(DioException)? onError,
  }) async {
    try {
      Response<T> response = await _dio.get<T>(
        path,
        queryParameters: queryParameters,
        options: options,
      );
      if (onSuccess != null) {
        onSuccess(response.data);
      }
      return response.data;
    } catch (e) {
      if (onError != null) {
        onError(e as DioException);
      } else {
        // 默认错误处理
        handleDioError(e as DioException);
      }
      return null;
    }
  }

  // POST请求方法
  Future<T?> post<T>(
    String path, {
    data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    Function(T?)? onSuccess,
    Function(DioException)? onError,
  }) async {
    try {
      Response<T> response = await _dio.post<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
      );
      if (onSuccess != null) {
        onSuccess(response.data);
      }
      return response.data;
    } catch (e) {
      if (onError != null) {
        onError(e as DioException);
      } else {
        handleDioError(e as DioException);
      }
      return null;
    }
  }
}
